package com.mdd.maduoduo.utils;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

public class BootReceiver  extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || intent.getAction() == null) return;

        // 重新注册短信接收器
        registerSmsReceiver(context);

        // 启动保活服务
        startKeepAliveService(context);
    }

    private void registerSmsReceiver(Context context) {
        try {
            ComponentName receiver = new ComponentName(context, PersistentSmsReceiver.class);
            PackageManager pm = context.getPackageManager();

            pm.setComponentEnabledSetting(receiver,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP);
        } catch (Exception e) {
            Log.e("BootReceiver", "Register SMS receiver failed", e);
        }
    }

    private void startKeepAliveService(Context context) {
        Intent serviceIntent = new Intent(context, SmsUploadService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(serviceIntent);
        } else {
            context.startService(serviceIntent);
        }
    }
}
